package auth

import (
	"admin/models/auth"
	"github.com/gin-gonic/gin"
	"gitlab.jkluck.vip/casino/golang/ca-common-util/library/log"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// RolePermissionRepoInterface 角色仓库接口
type RolePermissionRepoInterface interface {
	AddPermissionToRole(ctx *gin.Context, roleID int64, permIDs []int64) error
	RemovePermissionFromRole(ctx *gin.Context, roleID int64, permIDs []int64) error
	GetPermissionsByRoleId(roleID int64) ([]auth.Permission, error)
}

type RolePermissionRepo struct {
	db *gorm.DB
}

func NewRolePermissionRepo(db *gorm.DB) *RolePermissionRepo {
	return &RolePermissionRepo{db: db}
}

// AddPermissionToRole 为角色添加权限
// roleID: 角色ID
// permID: 权限ID
// db: 数据库连接
// 返回值: 错误信息
func (r *RolePermissionRepo) AddPermissionToRole(ctx *gin.Context, roleID int64, permIDs []int64) error {
	// 批量处理 需要操作的权限
	var rolePermissions []auth.RolePermission
	for _, permId := range permIDs {
		rolePermissions = append(rolePermissions, auth.RolePermission{
			RoleID:       roleID,
			PermissionID: permId,
		})
	}
	// 一次操作插入
	if err := r.db.Create(&rolePermissions).Error; err != nil {
		log.InfoCtx(ctx, "AddPermissionToRole", zap.Error(err))
		return err
	}
	return nil
}

// RemovePermissionFromRole 删除角色的某个权限
// roleID: 角色ID
// permID: 权限ID
// db: 数据库连接
// 返回值: 错误信息
func (r *RolePermissionRepo) RemovePermissionFromRole(ctx *gin.Context, roleID int64, permIDs []int64) error {
	var rolePermissions []auth.RolePermission
	for _, permId := range permIDs {
		rolePermissions = append(rolePermissions, auth.RolePermission{
			RoleID:       roleID,
			PermissionID: permId,
		})
	}
	if err := r.db.Where("role_id = ?", roleID).Delete(&rolePermissions).Error; err != nil {
		log.InfoCtx(ctx, "RemovePermissionFromRole", zap.Error(err))
		return err
	}
	return nil
}

// GetPermissionsByRoleId 查询角色拥有的所有权限
// roleID: 角色ID
// db: 数据库连接
// 返回值: 权限列表和错误信息
func (r *RolePermissionRepo) GetPermissionsByRoleId(roleID int64) ([]auth.Permission, error) {
	var perms []auth.Permission
	err := r.db.
		Table("permissions p").
		Joins("JOIN role_permissions rp ON rp.permission_id = p.id").
		Where("rp.role_id = ?", int64(roleID)).
		Find(&perms).Error
	return perms, err
}
